package com.villaday.idf.custom.pop;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.TextureView;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.m7.imkfsdk.KfStartHelper;
import com.moor.imkf.model.entity.CardInfo;
import com.villaday.idf.R;
import com.villaday.idf.custom.FastBlur;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.LoginEntity;
import com.villaday.idf.model.Presell_detail;
import com.villaday.idf.model3.MessageEntity;
import com.villaday.idf.model3.Messages;
import com.villaday.idf.model3.customerServiceStaffEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;

import razerdp.basepopup.BasePopupWindow;

public class ZXPop extends BasePopupWindow implements OkHttpUtil.OnDataListener {
    private Handler mHandler;
    private Context context;
    private Activity activity;
    private Presell_detail.BodyEntity body;
    private LoadingDialog loadingDialog;

    Gson gson = new GsonBuilder().create();
    private final SimpleDraweeView img_head;
    private final TextView tv_name;
    private final TextView tv_phone;
    private final TextView tv_chat;
    private customerServiceStaffEntity.BodyBean bodyzc;
    private final LinearLayout ll_online;
    private final LinearLayout ll_noonline;
    private final EditText et_phone;
    private final EditText et_message;
    private final ImageView img_send;
    private final TextView tv_noonline;
    private final View viwe_kefu;

    public ZXPop(final Context context, final Activity activity, Presell_detail.BodyEntity body) {
        super(context);
        this.context = context;
        this.activity = activity;
        this.body = body;
        findViewById(R.id.tv_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mHandler = new Handler();


        buildAnima();
        setBackground(0);
        setOutSideDismiss(true);
        setKeepSize(true);
        setBlurBackgroundEnable(true);
        img_head = findViewById(R.id.sdv_head);
        tv_name = findViewById(R.id.tv_name);

        tv_phone = findViewById(R.id.tv_phone);
        tv_chat = findViewById(R.id.tv_chat);

        ll_online = findViewById(R.id.ll_online);

        ll_noonline = findViewById(R.id.ll_noonline);

        et_phone = findViewById(R.id.et_phone);

        et_message = findViewById(R.id.et_message);

        img_send = findViewById(R.id.img_send);
        tv_noonline = findViewById(R.id.tv_noonline);

        viwe_kefu = findViewById(R.id.viwe_kefu);




        img_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (et_phone.getText().toString().length() == 0) {
                    ToastUtil.initToast(context, "请输入您的手机号码");
                } else if (et_message.getText().toString().length() == 0) {
                    ToastUtil.initToast(context, "请输入您的需求留言");

                } else {
                    loadingDialog = LoadingDialog.newInstance("提交中");
                    loadingDialog.show(activity.getFragmentManager(), "loading");
                    Map<String, Object> map = new HashMap<>();

                    Messages messages = new Messages(et_phone.getText().toString(), et_message.getText().toString());

                    OkHttpUtil.postJson(context, Constant.URL.messages, messages, map, new OkHttpUtil.OnDataListener() {
                        @Override
                        public void onResponse(String url, String json) {
                            LogeUtil.e("messages", json);
                            dismissLoading();
                            if (!TextUtils.isEmpty(json)) {
                                MessageEntity messageEntity = gson.fromJson(json, MessageEntity.class);
                                if ("200".equals(messageEntity.getCode())) {
                                    if (messageEntity.getBody().getStatus() == 1) {
                                        ToastUtil.initToast(context, "提交成功");
                                        dismiss();

                                    } else {
                                        ToastUtil.initToast(context, "提交失败");

                                    }

                                } else {
                                    ToastUtil.initToast(context, messageEntity.getMsg());
                                }
                            }

                        }

                        @Override
                        public void onFailure(String url, String error) {
                            dismissLoading();
                        }
                    });
                }


            }
        });


        tv_chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bodyzc != null && bodyzc.isOnline()) {
                    dismiss();
                  /*   Intent intent1 = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + "0755-26657792");
                intent1.setData(data);
                context.startActivity(intent1);*/
                    if (ZXPop.this.body.getImShareDTO() == null) {
                        return;
                    }

                    KfStartHelper helper = new KfStartHelper(activity);
                    LoginEntity userInfo = SharedPreferencesUtil.getUserInfo(getContext());
                    CardInfo ci = null;
                    try {
                        ci = new
                                CardInfo(ZXPop.this.body.getImShareDTO().getImageURL(),
                                ZXPop.this.body.getImShareDTO().getTitle(),
                                ZXPop.this.body.getImShareDTO().getSurrounding(),
                                PhoneUtil.handleBalance((Long.parseLong(ZXPop.this.body.getImShareDTO().getPrice()) / 100 + ""), 2),
                                ZXPop.this.body.getImShareDTO().getLinkURL());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //设置card
                    helper.setCard(ci);
                    //设置参数初始化
                    helper.initSdkChat("com.villaday.idf.7mss",
                            userInfo.getBody().getMember().getNickName() + "",
                            userInfo.getBody().getMember().getId() + "");
                }

            }
        });

        tv_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bodyzc != null && bodyzc.isOnline()) {
                    dismiss();
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + bodyzc.getMobile());
                    intent.setData(data);
                    context.startActivity(intent);

                }

            }
        });


        loadData();
    }

    private void loadData() {
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(activity.getFragmentManager(), "loading");
        Map<String, String> map = new HashMap<>();
        map.put("action", "assign");
        OkHttpUtil.getJSON(getContext(), Constant.URL.customerServiceStaff, map, this);

    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    // 必须实现，这里返回您的contentView
    // 为了让库更加准确的做出适配，强烈建议使用createPopupById()进行inflate
    @Override
    public View onCreateContentView() {
        return createPopupById(R.layout.zx);
    }


    private AnimationSet mAnimationSet;

    private void buildAnima() {
        ScaleAnimation mScaleAnimation = new ScaleAnimation(1f, 2f, 1f, 2f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        mScaleAnimation.setDuration(200);
        mScaleAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
        mScaleAnimation.setFillAfter(false);

        AlphaAnimation mAlphaAnimation = new AlphaAnimation(1, .2f);
        mAlphaAnimation.setDuration(400);
        mAlphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
        mAlphaAnimation.setFillAfter(false);

        mAnimationSet = new AnimationSet(false);
        mAnimationSet.setDuration(400);
        mAnimationSet.addAnimation(mScaleAnimation);
        mAnimationSet.addAnimation(mAlphaAnimation);
        mAnimationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismiss();
                    }
                }, 150);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }


    @Override
    protected Animation onCreateShowAnimation() {
        Animation showAnima = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
                1f,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                0);
        showAnima.setInterpolator(new DecelerateInterpolator());
        showAnima.setDuration(350);
        return showAnima;
    }

    @Override
    protected Animation onCreateDismissAnimation() {
        Animation exitAnima = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
                0f,
                Animation.RELATIVE_TO_PARENT,
                1f,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                0);
        exitAnima.setInterpolator(new DecelerateInterpolator());
        exitAnima.setDuration(350);
        return exitAnima;
    }


    @Override
    public void onResponse(String url, String json) {
        dismissLoading();
        LogeUtil.e("customerServiceStaff", json);

        if (!TextUtils.isEmpty(json)) {
            customerServiceStaffEntity customerServiceStaffEntity = gson.fromJson(json, customerServiceStaffEntity.class);
            if ("200".equals(customerServiceStaffEntity.getCode())) {
                bodyzc = customerServiceStaffEntity.getBody();
                // Glide.with(context).asBitmap().load(body.getProfilePicture()).into(img_head);

                img_head.setImageURI(bodyzc.getProfilePicture());
                tv_name.setText(bodyzc.getName());

                if (bodyzc.isOnline()) {
                    ll_online.setVisibility(View.VISIBLE);
                    viwe_kefu.setSelected(true);

                } else {
                    ll_noonline.setVisibility(View.VISIBLE);
                    tv_noonline.setVisibility(View.VISIBLE);
                    viwe_kefu.setSelected(false);

                }

            } else {
                ToastUtil.initToast(context, customerServiceStaffEntity.getMsg());

            }
        }

    }

    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
    }
}


